<template>
  <div class="code-login">
    <div class="code-login-title">{{ $t('login.code-login') }}</div>
    <div class="code-login-form">
      <el-form ref="codeRef" :model="codeForm" :rules="codeRules">
        <el-form-item prop="phone">
          <el-input
            v-model="codeForm.phone"
            :placeholder="$t('login.enter-phone')"
          />
        </el-form-item>
        <el-form-item prop="code">
          <div class="flex-1">
            <core-pin-input
              :modelValue="code"
              :error="codeError"
              type="numeric"
              @complete="handleComplete"
              @incomplete="handleIncomplete"
            ></core-pin-input>
          </div>
          <el-button
            class="get-code-button"
            :loading="getCodeLoading"
            @click="handleGetCode"
            >{{ codeButtonTxt }}</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="send-button display-flex">
      <el-button
        class="flex-1"
        type="primary"
        :loading="loginLoading"
        @click="handleLogin"
        >{{ $t('login.login') }}</el-button
      >
    </div>
    <div class="display-flex">
      <el-button class="flex-1" @click="handleBack">{{
        $t('login.back')
      }}</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { usePreferencesStore } from '@/stores'
import { delay } from '@/utils'
import { phoneRegex } from '@/utils/modules/regexp'
import type { FormInstance, FormRules } from 'element-plus'
import { onUnmounted, reactive, ref, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const { t } = useI18n()
const preferencesStore = usePreferencesStore()

const codeForm = ref({
  phone: '',
  code: ''
})
const codeRules = reactive<FormRules<typeof codeForm.value>>({
  phone: [
    { required: true, message: t('login.enter-phone'), trigger: 'blur' },
    {
      pattern: phoneRegex,
      message: t('login.enter-correct-phone'),
      trigger: ['blur', 'change']
    }
  ],
  code: [
    { required: true, message: t('login.enter-verify-code'), trigger: 'blur' }
  ]
})
const codeRef = useTemplateRef<FormInstance>('codeRef')
const codeButtonTxt = ref(t('login.get-verify-code'))
const getCodeLoading = ref(false)
let timer: number
const handleGetCode = async () => {
  try {
    if (!getCodeLoading.value) {
      await codeRef.value?.validateField('phone')
      getCodeLoading.value = true
      await delay(500)
      let time = 60
      codeButtonTxt.value = t('login.wait-retry', [time--])
      timer = window.setInterval(() => {
        if (time === 0) {
          codeButtonTxt.value = t('login.get-verify-code')
          window.clearInterval(timer)
          getCodeLoading.value = false
        } else {
          codeButtonTxt.value = t('login.wait-retry', [time--])
        }
      }, 1000)
    }
  } catch (error) {
    getCodeLoading.value = false
    return error
  }
}

const code = ref(['', '', '', '', '', ''])
const codeError = ref(false)
const handleComplete = (val: string[]) => {
  codeError.value = false
  codeForm.value.code = val.join('')
  codeRef.value?.validateField('code')
}
const handleIncomplete = () => {
  codeError.value = true
  codeForm.value.code = ''
  codeRef.value?.validateField('code')
}

const loginLoading = ref(false)
const handleLogin = () => {
  loginLoading.value = true
  codeRef.value
    ?.validate()
    .then(async () => {
      await delay(500)
      if (route.query.redirect) {
        router.replace(route.query.redirect as string)
      } else {
        router.replace('/')
      }
    })
    .catch((error: typeof codeRules) => {
      if (error.code) codeError.value = true
    })
    .finally(() => {
      loginLoading.value = false
    })
}

const handleBack = () => {
  router.replace('/login/enter')
}

watch(
  () => preferencesStore.general.lang.language,
  () => {
    if (codeRules.phone && Array.isArray(codeRules.phone)) {
      codeRules.phone[0].message = t('login.enter-phone')
      codeRules.phone[1].message = t('login.enter-correct-phone')
    }
    if (codeRules.code && Array.isArray(codeRules.code)) {
      codeRules.code[0].message = t('login.enter-verify-code')
      codeError.value = true
    }
    if (!getCodeLoading.value) {
      codeButtonTxt.value = t('login.get-verify-code')
    }
  }
)

onUnmounted(() => {
  window.clearInterval(timer)
})

defineOptions({
  name: 'CoreCodeLogin'
})
</script>

<style scoped lang="scss">
.code-login {
  margin: 24px 54px;

  .code-login-title {
    margin-bottom: 22px;
    font-size: 36px;
    font-weight: 700;
  }

  .get-code-button {
    width: 200px;
    margin-left: 8px;
  }

  .send-button {
    padding-top: 8px;
    margin-bottom: 16px;
  }
}
</style>
